package handler.v2;

import java.util.function.Consumer;

public class InitFeeCalcHandler {
    private  HandlerNode handlerNode = new HandlerNode();

    InitFeeCalcHandler addLeft(FeeCalcHandler handler){
        handlerNode.addLeft(new HandlerNode(handler));
        return this;
    }

    InitFeeCalcHandler addRight(FeeCalcHandler handler){
        handlerNode.addRight(new HandlerNode(handler));
        return this;
    }


    public Result calc(Param param) {
        return handlerNode.handler.handler(param, new Result());
    }

    public void getAll(Consumer<HandlerNode> consumer){
        HandlerNode temp = handlerNode;
        while (temp != null){
            consumer.accept(temp);
            temp = temp.next;
        }
    }
    class HandlerNode{

        HandlerNode next;

        FeeCalcHandler handler;

        public HandlerNode(){}

        private HandlerNode(FeeCalcHandler leaveHandler){
            this.handler = leaveHandler;
        }

        public void addRight(HandlerNode node){
            if(handlerNode.handler == null){
                handlerNode = node;
                return;
            }
            HandlerNode tailNode = getTail(handlerNode);
            tailNode.handler.nextHandler= node.handler;
            tailNode.next = node;
        }

        public HandlerNode getTail(HandlerNode node){
            if(node.next == null || node.next.handler == null){
                return node;
            }
            return getTail(node.next);
        }

        public void addLeft(HandlerNode node){
            if(handlerNode.handler == null){
                handlerNode = node;
                return;
            }
            HandlerNode temp = handlerNode;
            handlerNode = node;
            handlerNode.next = temp;
            handlerNode.handler.nextHandler = temp.handler;
        }
    }
}
